/**
 * EventVisualizer - 事件可视化系统
 * 在村庄场景中显示游戏事件
 */

// 事件类型配置
const EVENT_TYPES = {
  resource_found: {
    icon: '💎',
    color: '#4CAF50',
    animation: 'bounce',
    duration: 5000
  },
  visitor_arrived: {
    icon: '👋',
    color: '#2196F3',
    animation: 'wave',
    duration: 8000
  },
  disaster: {
    icon: '⚠️',
    color: '#F44336',
    animation: 'shake',
    duration: 10000
  },
  celebration: {
    icon: '🎉',
    color: '#FF9800',
    animation: 'sparkle',
    duration: 6000
  },
  quest_available: {
    icon: '❗',
    color: '#9C27B0',
    animation: 'pulse',
    duration: -1 // 持续显示直到完成
  },
  achievement: {
    icon: '🏆',
    color: '#FFD700',
    animation: 'glow',
    duration: 7000
  }
}

class EventVisualizer {
  constructor(ctx) {
    this.ctx = ctx
    this.activeEvents = []
  }

  /**
   * 添加事件
   */
  addEvent(event) {
    const config = EVENT_TYPES[event.type]
    if (!config) {
      console.warn('Unknown event type:', event.type)
      return
    }

    const visualEvent = {
      id: event.id || Date.now() + Math.random(),
      type: event.type,
      position: event.position || { x: 375, y: 200 },
      config: config,
      startTime: Date.now(),
      data: event.data || {}
    }

    this.activeEvents.push(visualEvent)
    return visualEvent.id
  }

  /**
   * 移除事件
   */
  removeEvent(eventId) {
    const index = this.activeEvents.findIndex(e => e.id === eventId)
    if (index !== -1) {
      this.activeEvents.splice(index, 1)
    }
  }

  /**
   * 渲染所有事件
   */
  render(timestamp) {
    // 清理过期事件
    this.activeEvents = this.activeEvents.filter(event => {
      if (event.config.duration === -1) return true
      return (timestamp - event.startTime) < event.config.duration
    })

    // 渲染每个事件
    this.activeEvents.forEach(event => {
      this.renderEvent(event, timestamp)
    })
  }

  /**
   * 渲染单个事件
   */
  renderEvent(event, timestamp) {
    const { position, config } = event
    const elapsed = timestamp - event.startTime

    // 应用动画
    const animatedPos = this.applyAnimation(position, config.animation, elapsed)

    // 绘制事件图标背景
    const bgAlpha = this.getBackgroundAlpha(config.animation, elapsed)
    this.ctx.setFillStyle(`${config.color}${Math.floor(bgAlpha * 255).toString(16).padStart(2, '0')}`)
    this.ctx.beginPath()
    this.ctx.arc(animatedPos.x, animatedPos.y, 30, 0, Math.PI * 2)
    this.ctx.fill()

    // 绘制外圈光晕
    const gradient = this.ctx.createRadialGradient(
      animatedPos.x, animatedPos.y, 0,
      animatedPos.x, animatedPos.y, 40
    )
    gradient.addColorStop(0, `${config.color}80`)
    gradient.addColorStop(1, `${config.color}00`)
    
    this.ctx.setFillStyle(gradient)
    this.ctx.beginPath()
    this.ctx.arc(animatedPos.x, animatedPos.y, 40, 0, Math.PI * 2)
    this.ctx.fill()

    // 绘制图标
    this.ctx.setFontSize(32)
    this.ctx.setTextAlign('center')
    this.ctx.setTextBaseline('middle')
    this.ctx.fillText(config.icon, animatedPos.x, animatedPos.y)

    // 绘制事件标题（如果有）
    if (event.data.title) {
      this.ctx.setFontSize(20)
      this.ctx.setFillStyle('#333')
      this.ctx.fillText(event.data.title, animatedPos.x, animatedPos.y + 50)
    }

    // 绘制特殊效果
    this.renderSpecialEffects(event, animatedPos, elapsed)
  }

  /**
   * 应用动画效果
   */
  applyAnimation(position, animation, elapsed) {
    const pos = { ...position }

    switch (animation) {
      case 'bounce':
        // 弹跳动画
        pos.y -= Math.abs(Math.sin(elapsed / 300) * 20)
        break

      case 'wave':
        // 波浪动画
        pos.x += Math.sin(elapsed / 500) * 10
        pos.y += Math.cos(elapsed / 700) * 5
        break

      case 'shake':
        // 震动动画
        pos.x += Math.sin(elapsed / 50) * 5
        pos.y += Math.cos(elapsed / 50) * 5
        break

      case 'sparkle':
        // 闪烁动画
        const scale = 1 + Math.sin(elapsed / 200) * 0.2
        pos.scale = scale
        break

      case 'pulse':
        // 脉冲动画
        const pulseScale = 1 + Math.sin(elapsed / 400) * 0.15
        pos.scale = pulseScale
        break

      case 'glow':
        // 发光动画
        const glowIntensity = Math.sin(elapsed / 300) * 0.5 + 0.5
        pos.glow = glowIntensity
        break
    }

    return pos
  }

  /**
   * 获取背景透明度
   */
  getBackgroundAlpha(animation, elapsed) {
    if (animation === 'sparkle' || animation === 'glow') {
      return 0.6 + Math.sin(elapsed / 300) * 0.2
    }
    return 0.8
  }

  /**
   * 渲染特殊效果
   */
  renderSpecialEffects(event, position, elapsed) {
    const { config } = event

    switch (config.animation) {
      case 'sparkle':
        this.renderSparkles(position, elapsed)
        break

      case 'glow':
        this.renderGlow(position, elapsed, config.color)
        break

      case 'pulse':
        this.renderPulseRings(position, elapsed, config.color)
        break

      case 'shake':
        this.renderWarningLines(position, elapsed)
        break
    }
  }

  /**
   * 渲染闪光粒子
   */
  renderSparkles(position, elapsed) {
    for (let i = 0; i < 8; i++) {
      const angle = (i / 8) * Math.PI * 2 + elapsed / 500
      const distance = 40 + Math.sin(elapsed / 300 + i) * 10
      const x = position.x + Math.cos(angle) * distance
      const y = position.y + Math.sin(angle) * distance
      const alpha = Math.sin(elapsed / 200 + i) * 0.5 + 0.5

      this.ctx.setFillStyle(`rgba(255, 215, 0, ${alpha})`)
      this.ctx.beginPath()
      this.ctx.arc(x, y, 3, 0, Math.PI * 2)
      this.ctx.fill()
    }
  }

  /**
   * 渲染发光效果
   */
  renderGlow(position, elapsed, color) {
    const intensity = Math.sin(elapsed / 300) * 0.5 + 0.5
    const radius = 50 + intensity * 20

    const gradient = this.ctx.createRadialGradient(
      position.x, position.y, 0,
      position.x, position.y, radius
    )
    gradient.addColorStop(0, `${color}${Math.floor(intensity * 100).toString(16).padStart(2, '0')}`)
    gradient.addColorStop(1, `${color}00`)

    this.ctx.setFillStyle(gradient)
    this.ctx.beginPath()
    this.ctx.arc(position.x, position.y, radius, 0, Math.PI * 2)
    this.ctx.fill()
  }

  /**
   * 渲染脉冲环
   */
  renderPulseRings(position, elapsed, color) {
    for (let i = 0; i < 3; i++) {
      const offset = i * 500
      const progress = ((elapsed + offset) % 1500) / 1500
      const radius = 30 + progress * 40
      const alpha = 1 - progress

      this.ctx.setStrokeStyle(`${color}${Math.floor(alpha * 255).toString(16).padStart(2, '0')}`)
      this.ctx.setLineWidth(3)
      this.ctx.beginPath()
      this.ctx.arc(position.x, position.y, radius, 0, Math.PI * 2)
      this.ctx.stroke()
    }
  }

  /**
   * 渲染警告线条
   */
  renderWarningLines(position, elapsed) {
    const lineCount = 4
    for (let i = 0; i < lineCount; i++) {
      const angle = (i / lineCount) * Math.PI * 2 + elapsed / 100
      const length = 50 + Math.sin(elapsed / 200 + i) * 10

      this.ctx.setStrokeStyle('#F44336')
      this.ctx.setLineWidth(3)
      this.ctx.beginPath()
      this.ctx.moveTo(position.x, position.y)
      this.ctx.lineTo(
        position.x + Math.cos(angle) * length,
        position.y + Math.sin(angle) * length
      )
      this.ctx.stroke()
    }
  }

  /**
   * 点击检测
   */
  hitTest(x, y) {
    for (let i = this.activeEvents.length - 1; i >= 0; i--) {
      const event = this.activeEvents[i]
      const { position } = event
      const dx = x - position.x
      const dy = y - position.y
      const distance = Math.sqrt(dx * dx + dy * dy)

      if (distance <= 40) {
        return event
      }
    }

    return null
  }

  /**
   * 获取所有活动事件
   */
  getActiveEvents() {
    return this.activeEvents
  }

  /**
   * 清除所有事件
   */
  clearAll() {
    this.activeEvents = []
  }

  /**
   * 清除指定类型的事件
   */
  clearByType(type) {
    this.activeEvents = this.activeEvents.filter(e => e.type !== type)
  }
}

export default EventVisualizer
export { EVENT_TYPES }
